﻿using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace MyOCR_WPF.TranslateHelper
{
    class YouDaoTranslate : ITranslate
    {
        // 有道云中开通对应服务应用的 API Key 建议开通应用的时候多选服务
        private static String clientId;
        // 有道云中开通对应服务应用的 Secret Key
        private static String clientSecret;

        static TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        Int64 currentTime = Convert.ToInt64(ts.TotalSeconds);

        public YouDaoTranslate()
        {
            clientId = ConfigurationManager.AppSettings["YouDao_Id"];
            clientSecret = ConfigurationManager.AppSettings["YouDao_Key"];
        }

        public string SendContent(string content)
        {
            string authHost = "https://openapi.youdao.com/api";
            RestClient restClient = new RestClient(authHost);
            RestRequest restRequest = new RestRequest(Method.POST);

            restRequest.AddParameter("q", content);
            restRequest.AddParameter("from", "auto");
            restRequest.AddParameter("to", "auto");
            restRequest.AddParameter("appKey", clientId);
            restRequest.AddParameter("salt", "011225");
            restRequest.AddParameter("sign", getSign(content));
            restRequest.AddParameter("signType", "v3");
            restRequest.AddParameter("curtime", currentTime);

            var result = restClient.Execute(restRequest);

            try
            {
                var lst = new List<string>();
                dynamic json = JsonConvert.DeserializeObject(result.Content);
                foreach (var item in json.translation)
                {
                    lst.Add(item.ToString());
                }

                return string.Join("\r\n\r\n    ", lst);
            }
            catch (Exception)
            {
                return "出现了点小问题";
            }
        }

        protected string getSign(string q)
        {
            HashAlgorithm algorithm = new SHA256CryptoServiceProvider();
            string signStr = clientId + q + "011225" + currentTime + clientSecret;
            Byte[] inputBytes = Encoding.UTF8.GetBytes(signStr);
            Byte[] hashedBytes = algorithm.ComputeHash(inputBytes);
            return BitConverter.ToString(hashedBytes).Replace("-", "");
        }
    }
}
